#include <windows.h>
#include <QtGui>
#include <qt_windows.h>
#ifdef D3DX
#include <d3d9.h>
#endif
#include "DirectXCapture.h"

DirectXCapture::DirectXCapture(QWidget*wnd)
{
#ifdef D3DX
	m_pd3dDevice = NULL;
	m_pD3D = NULL;
	m_pSurface = NULL;
	m_SelSurface = NULL;

	parent = wnd;
	if(!InitDirectX()){
		qDebug("Init DirectX failed");
	}
	else{
		D3DDISPLAYMODE mode;
		m_pd3dDevice->GetDisplayMode(0, &mode);
		ScreenWidth = mode.Width;
		ScreenHeight = mode.Height;
	}
#endif
}

DirectXCapture::~DirectXCapture(){

}

bool DirectXCapture::InitDirectX(){
#ifdef D3DX
	m_pD3D = Direct3DCreate9( D3D_SDK_VERSION);
	if(!m_pD3D)
		return false;
	D3DPRESENT_PARAMETERS d3dpp = {0};
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	HRESULT hrResult = m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, parent->winId(),
											 D3DCREATE_HARDWARE_VERTEXPROCESSING,
											 &d3dpp, &m_pd3dDevice );
	if(FAILED(hrResult))return false;
#endif
	return true;
}

void DirectXCapture::Capture(){
#ifdef D3DX
	myTimer.start();
	m_pd3dDevice->CreateOffscreenPlainSurface(ScreenWidth, ScreenHeight,
		  D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &m_pSurface, NULL);
	m_pd3dDevice->GetFrontBufferData(0, m_pSurface);
#endif
}

void DirectXCapture::Release(){
#ifdef D3DX
	m_pSurface->Release();
#endif
	WorkTime = myTimer.elapsed();
}

int DirectXCapture::GetTime(){
	return WorkTime;
}

void DirectXCapture::MakeScreenshot(int x1, int y1, int x2, int y2){
#ifdef D3DX
	m_pd3dDevice->CreateOffscreenPlainSurface(x2-x1, y2-y1,
		  D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &m_SelSurface, NULL);
	RECT src = {x1,y1,x2,y2};
	RECT dest = {0,0,x2-x1,y2-y1};
	SelRect = dest;
	HRESULT res = m_pd3dDevice->StretchRect(m_pSurface,&src,m_SelSurface,&dest,D3DTEXF_NONE);
	if(res == D3DERR_INVALIDCALL) qDebug("Stretch error\n");
#endif
}

void DirectXCapture::SaveToFile(char* filename){
#ifdef D3DX
	D3DXSaveSurfaceToFile(filename,D3DXIFF_JPG,m_SelSurface,NULL,NULL);
#endif
}

QColor DirectXCapture::GetAverage(){
#ifdef D3DX
	IDirect3DSurface9* surf;
	m_pd3dDevice->CreateOffscreenPlainSurface(1, 1,
		  D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &surf, NULL);
	RECT dest ={0,0,1,1};
	m_pd3dDevice->StretchRect(m_pSurface,&SelRect,surf,&dest,D3DTEXF_NONE);
	surf->Release();
#endif
	return QColor(0,0,0);
}

